var BASE_URL = 'http://jinzhidata.com/v2'

//读取cookie
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    }
    return null;
}

$(function () {
    $("#wechatLogin").click(function () {
        var redirectUrl = encodeURIComponent(BASE_URL + '/wechatLogin')
        location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc634f9a658b7c3eb&redirect_uri=" + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=login#wechat_redirect"
    });

    if (getCookie("accessToken")) {
        $.ajax({
            type: "get",
            url: BASE_URL + "/getUserInfo",
            contentType: 'application/json',
            dataType: "json",
            success: function (response) {
                if (response.code === 0) {
                    var data = response.data
                    $("#userName").html(data.userName)
                    $("#userPoints").html(data.userPoints)
                    $("#userAvatar").attr("src", data.userAvatar);
                    // 登录后删除登录按钮监听事件，绑定退出按钮监听事件
                    $("#wechatLogin").unbind("click");
                    $("#logout").click(function () {
                        location.href = BASE_URL + "/logout"
                    })
                }
            }
        })
    }

})
